<?php
class AgencyAction extends Action {
	//display the index page of Agency
	public function index() {
		if (!$this->isLogin())
			$this->error(L('pls_login_first'));	
		
		$this->display();
	}
	
	public function loadAgency() {
		$agencyList = D('Agency')->getAgencyBriefList();
		
		if ($agencyList === false) {
			jsonecho(0, L('load_data_failed'));
		} else if (empty($agencyList)) {
			jsonecho(2, L('no_data'));
		} else {
			echo json_encode(array(status => 1, data => $agencyList));
		}		
	}
	
	public function loadAgencyPage() {
		$nowPage = isset($_POST['p'])?$_POST['p']:1;
		//search condition
		$sName = isset($_POST['sName'])?$_POST['sName']:'';
		$sTime = isset($_POST['sTime'])?$_POST['sTime']:'';
		$eTime = isset($_POST['eTime'])?$_POST['eTime']:'';
		$map = array();
		if (!empty($sName)) {
			$map['name'] = array('like', "%$sName%");
		} else {
			if (!empty($sTime)){
				$map['createdtime'] = array('egt', $sTime);
			}
			if (!empty($eTime)){
				$map['createdtime'] = array('elt', $eTime);
			}
		}
		$Agency = D('Agency');
		$count = $Agency->where($map)->getCount();
		
		import('ORG.Util.Page');
		$Page = new Page($count, 15, '/Admin/Agency/loadAgencyPage');
		
		$o = array('createdtime'=> 'desc');
		$list = $Agency->where($map)->order($o)->page($nowPage.','.$Page->listRows)->select();

		$totalPages = $Page->getTotalPages();
		$pageInfo=array(totalPages => $totalPages, nowPage => $nowPage);
		//print_r($pageInfo);
		if ($list === false) {
			jsonecho(0, L('load_data_failed'));
		} else if (empty($list)) {
			jsonecho(2, L('no_data'));
		} else {
			echo json_encode(array(status => 1, data => $list, page => $pageInfo));
		}
	}
	
	public function isLogin() {
		return  isset($_SESSION[C('ADMIN_AUTH_KEY')]) ? true: false;
	}
	
	public function getAgencyInfo() {
		$id = $this->_post('id');
		//echo $id;
		$agency = D('Agency')->getAgencyInfoById($id);
		//print_r($agency);
		if (!empty($agency)) {
			echo json_encode(array(status=>1, data=>$agency));
		}
	}
	
	// show add Agency page
	public function add() {
		$this->display();
	}
	
	//perform the add Agency
	public function doAdd() {
		
		$Agency = D('Agency');
		if (!$Agency->create()) {
			$this->error($Agency->getError(), __URL__."/add");
		}
		
		$email = $_POST['email'];
		$r = $Agency->where(array(email=>$email))->field('id')->find();
		if ($r) {
			$this->error(L('email_exist'), __URL__."/add");
		}
		
		$data['name'] = $_POST['name'];
		$data['email'] = $_POST['email'];
		$data['password'] = md5($_POST['password']);
		$data['phone'] = $_POST['phone'];
		$data['logo'] = $_POST['logo'];
		$data['roadnumber'] = $_POST['roadnumber'];
		$data['roadname'] = $_POST['roadname'];
		$data['roaddesc'] = $_POST['roaddesc'];
		$data['postcode'] = $_POST['postcode'];
		$data['city'] = $_POST['city'];
		$data['confirmid'] = 1;
		$data['createdtime'] = date('Y-m-d H:i:s',time());
		
		$id = $Agency->add($data);
		if ($id > 0) {
			$this->success(L('add_success'), "/Admin/Agency/index");
		} else {
			$this->error(L('add_failed'), __URL__+"/add");
		}
	}
	
	public function doEdit() {
		$email = $this->_post('email');
		if(empty($email))  {
			jsonecho(1,L('email_require'));
		}
		 
		$Agency = D('Agency');
		if (!$Agency->create()) {
			$errorMsg = $Agency->getError();
			jsonecho(2, L($errorMsg));
		}
		
		$agencyId = $this->_post('agencyId');
		if (!isset($agencyId)) {
			jsonecho (3, L('edit_failed'));
		}
		
		$email = $this->_post('email');
		$res = $Agency->getAgencyEmailById($agencyId);
		if ($res['email'] != $email){
			if($Agency->emailExisted($email)) {
				jsonecho (4, L('email_existed'));
			}
		}
		
		$newPassword = $this->_post('newPassword');
		if (!empty($newPassword)) {
			$data['password'] = md5($newPassword);
		}
		$data['id'] = $agencyId;
		$data['email'] = $email;
		$data['name'] = $this->_post('name');
		$data['road_number']= $this->_post('road_number');
		$data['road_name'] = $this->_post('road_name');
		$data['road_desc'] = $this->_post('road_desc');
		$data['city'] = $this->_post('city');
		$data['postcode'] = $this->_post('postcode');
		$data['phone'] = $this->_post('phone');
		$data['logo'] = $this->_post('logo');
		$data['firstname'] = $this->_post('firstname');
		$data['lastname'] = $this->_post('lastname');
		$data['contactPhone'] = $this->_post('contactPhone');
		$data['contactEmail'] = $this->_post('contactEmail');
		$data['confirmid'] = $this->_post('confirmid');
		$data['statusid'] = $this->_post('statusid');
		
		$result = $Agency->save($data);
		if ($result === false) {
			jsonecho(5, L('edit_failed'));
		}

		jsonecho(0);
	}
	
	public function import() {
		$this->display();
	}
	
	public function doImport() {
		//upload file
		import('ORG.Net.UploadFile');
		$config['savePath'] = './Uploads/';
		$config['maxSize'] = '104857600'; //100M
		$config['allowExts'] = array('xls', 'xlsx');
		$upload = new UploadFile($config);
		if(!$upload->upload()) {
			jsonecho(0, L('import_failed'));
		}
		$info = $upload->getUploadFileInfo();
		
		//parse file
		$filetmpname = './Uploads/'.$info[0]['savename'];
		vendor('Classes.PHPExcel');
		$objPHPExcel = PHPExcel_IOFactory::load($filetmpname);
		$arrExcel = $objPHPExcel->getSheet(0)->toArray();
		//delete the first row
		array_shift($arrExcel);
		
		//get the column name from database
		$Agency = M('Agency');
		$fieldarr = $Agency->query("describe ".C('DB_PREFIX')."agency");
		foreach($fieldarr as $v){
			if ($v['Field'] != 'id' && $v['Field'] != 'logo' && 
				$v['Field'] != 'statusid' && $v['Field'] != 'login_count' &&
				$v['Field'] != 'login_ip' && $v['Field'] != 'last_login_time') {
				$field[] = $v['Field'];
			}
		}
		
		//combine field
		foreach($arrExcel as $key => $v){
			//For password encryption
			$v[2] = md5($v[2]);
			$v[15] = date('Y-m-d h:i:s', time());
			$fields[] = array_combine($field, $v);
		}

		if(!$Agency->addAll($fields)){
            jsonecho(0, L('import_failed'));
        }
        jsonecho(1, L('import_success'));
	}
	
	function doDelete() {
		$ids = $_POST['ids'];

		$result = D('Agency')->deleteAgencyByIds($ids);
		if ($result === false) {
			jsonecho(0, L('delete_failed'));
		} else {
			jsonecho(1);
		}
	}
}